package natappvip.liujinliang.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import natappvip.liujinliang.exception.FileIOException;
import natappvip.liujinliang.model.FileEle;
import natappvip.liujinliang.service.FileMetaDataService;
import natappvip.liujinliang.util.FileHandler;
import natappvip.liujinliang.util.PropertiesUtil;

/**
 * @ClassName:  FileMetaDataLocalServiceImpl   
 * @Despt: 本地文件元信息接口实现   
 * @Auth: Liujinliang 
 * @Date: 2018年7月29日 下午9:37:29
 */
public class FileMetaDataLocalServiceImpl implements FileMetaDataService {

	private static Logger logger = LoggerFactory.getLogger(FileMetaDataLocalServiceImpl.class);
	
	@Override
	public String record(FileEle ele) {
		int res = FileHandler.record(ele, PropertiesUtil.getProperty("mdata"));
		if (res == -1) {
			throw new FileIOException("记录文件元信息失败");
		}
		return ele.toString();
	}
	
	@Override
	public String record(String mdata) {
		int res = FileHandler.record(mdata, PropertiesUtil.getProperty("mdata"));
		if (res == -1) {
			throw new FileIOException("记录文件元信息失败");
		}
		return mdata;
	}

	@Override
	public String fetch(String uuid) {
		File file = new File(PropertiesUtil.getProperty("mdata"));  	// 从该文件中搜索uuid=id的文件信息元
		String line = null;							// 用来存储文件标识为id的信息元
		
		try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
			while((line = reader.readLine()) != null) {	// 遍历文件每一行
				if (line.startsWith("uuid:" + uuid)) {	// 命中行 
					return "文件系统记录：" + line;
				} 
			}
		} catch (FileNotFoundException e) {
			logger.info("mdata.txt文件不存在或者文件路径有误");
			throw new FileIOException(e.getMessage());
		} catch (IOException e) {
			throw new FileIOException(e.getMessage());
		}
		return line;
	}

	@Override
	public void remove(String uuid) {
		FileHandler.delRecord(uuid);
	}

}
